<?php
namespace App\Controller;

class LivesController extends AppController{

    public $_page_num = 30;
    public function initialize()
    {
        parent::initialize();
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：获取指定的直播
   * */
    public function getInfo()
    {
        $id = $this->request->getData("id");
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        $lives = $this->Lives->findById($id)->first();
        if(empty($lives)){
            $this->G->error("live_error");
            return null;
        }
        $lives['play_url'] = [];
        $lives['push_url'] = '';
        if($lives['status'] == 'living'){
             $now = time();
             $this->loadComponent('Live');
             $lives['push_url'] = $this->Live->getPushUrl($lives['id'],$now + 86400);
             $push = $this->Live->setStreamStatus($lives['id'],1,$now + 86400);
             if($push['status'] == 400){
                 $this->G->error("stream_status_set_error");
                 return null;
             }
             $arr = $this->Live->getPlayUrl($lives['id']);
             $lives['play_url']['rtmp'] = $arr[0];
             $lives['play_url']['flv'] = $arr[1];
             $lives['play_url']['m3u8'] = $arr[2];
        }
        $this->loadComponent('TextareaCache');
        $content = $this->TextareaCache->getVal('lives', $id);
        $this->loadComponent('ContentFormat');
        $lives['content']  = empty($content) ? '' : $this->ContentFormat->add($content['content']);
        $lives['live_time'] = date('Y-m-d H:i:s', $lives['live_time']);
        $lives['add_time'] = date('Y-m-d H:i:s', $lives['add_time']);
        $this->G->success("Success", $lives);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：获取普通直播列表
   * */
    public function getList()
    {
        $data = $this->request->getData();
        $where = [];
        if(isset($data['enabled']) && is_numeric($data['enabled'])){
            $where['enabled'] = $data['enabled'];
        }
        if(!empty($data['status'])){
            $where['status in'] = $data['status'];
        }
        $page = empty($data['page']) ? 1 :$data['page'];
        if(!empty($data['title'])){
            $where['title like'] = '%'.$data['title'].'%';
        }
        $live = $this->Lives->find()
            ->where($where)
            ->limit($this->_page_num)
            ->page($page);
        $result = [];
        $result['pageTotal'] = ceil($live->count()/$this->_page_num);
        $result['list'] = [];
        $live = $live->toArray();
        $this->loadComponent('Live');
        if(!empty($live)){
            $now = time();
            foreach ($live as $k=>$v){
                $live[$k]['live_time'] = date('Y-m-d H:i:s', $v['live_time']);
                $live[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $live[$k]['play_url'] = [];
                $live[$k]['push_url'] = '';
                 if($v['status'] == 'living'){
                     $live[$k]['push_url'] = $this->Live->getPushUrl($v['id'],$now + 86400);
                     $push = $this->Live->setStreamStatus($v['id'],1,$now + 86400);
                     if($push['status'] == 400){
                         $this->G->error($push['msg']);
                         return null;
                     }
                     $arr = $this->Live->getPlayUrl($v['id']);
                     $live[$k]['play_url']['rtmp'] = $arr[0];
                     $live[$k]['play_url']['flv'] = $arr[1];
                     $live[$k]['play_url']['m3u8'] = $arr[2];
                 }
                $result['list'][] = $live[$k];
            }
        }
        $this->G->success('Success', $result);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：删除直播
   * */
    public function delete()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $ids = $this->request->getData("ids");
        if(empty($ids) || !is_array($ids)){
            $this->G->error("ids_error");
            return null;
        }
        $this->loadComponent('LiveCache');
        $this->loadModel('CategoryContents');
        $this->LiveCache->deleteList();
        $this->Lives->deleteAll(['id in'=>$ids]);
        $this->CategoryContents->deleteAll(['content_id in'=>$ids,'content_type'=>'lives']);
        $this->G->success("Success");
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：新增直播
   * */
    public function add()
    {
        $title = $this->request->getData("title");
        $img = $this->request->getData("img");
        $author = $this->request->getData("author");
        $enabled = $this->request->getData("enabled");
        $status = $this->request->getData("status");
        $live_time = $this->request->getData("live_time");
        $view_group = $this->request->getData("view_group");
        $content = $this->request->getData("content");
        if(empty($author)){
            $this->G->error("author_error");
            return null;
        }
        if(empty($title)){
            $this->G->error("title_error");
            return null;
        }
        if(!in_array($status, ['notice','living','playback','closed'])){
            $this->G->error("status_error");
            return null;
        }
        if(!in_array($view_group, ['all','vip'])){
            $this->G->error("view_group_error");
            return null;
        }
        if(empty($content)){
            $this->G->error("content_error");
            return null;
        }
        $live = $this->Lives->newEntity();
        $live->title = $title;
        $live->img = $img;
        $live->author = $author;
        $live->status = $status;
        $live->enabled = $enabled;
        $live->live_time = strtotime($live_time);
        $live->view_group = $view_group;
        $live->add_time = time();
        $live_save = $this->Lives->save($live);
        $this->loadComponent('TextareaCache');
        $this->loadComponent('ContentFormat');
        $content  = $this->ContentFormat->clean($content)[0];
        $this->TextareaCache->add('lives', $live_save->id, $content);
        $this->loadComponent('LiveCache');
        $this->LiveCache->deleteList();
        $this->G->success("Success");
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：修改直播
   * */
    public function update()
    {
        $id = $this->request->getData("id");
        $title = $this->request->getData("title");
        $img = $this->request->getData("img");
        $author = $this->request->getData("author");
        $enabled = $this->request->getData("enabled");
        $status = $this->request->getData("status");
        $live_time = $this->request->getData("live_time");
        $view_group = $this->request->getData("view_group");
        $replay_url = $this->request->getData("replay_url");
        $content = $this->request->getData("content");
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        if(empty($author)){
            $this->G->error("author_error");
            return null;
        }
        if(empty($title)){
            $this->G->error("title_error");
            return null;
        }
        if(!in_array($status, ['notice','living','playback','closed'])){
            $this->G->error("status_error");
            return null;
        }
        if(!in_array($view_group, ['all','vip'])){
            $this->G->error("view_group_error");
            return null;
        }
        if(empty($content)){
            $this->G->error("content_error");
            return null;
        }
        $lives = $this->Lives->findById($id)->select(['id','record_info'])->first();
        if(empty($lives)){
            $this->G->error("live_error");
            return null;
        }
        $record_info = json_decode($lives['record_info'], true);
        $record_info['video_url'] = $replay_url;
        $live = $this->Lives->newEntity();
        $live->id = $id;
        $live->title = $title;
        $live->img = $img;
        $live->author = $author;
        $live->status = $status;
        $live->enabled = $enabled;
        $live->live_time = strtotime($live_time);
        $live->view_group = $view_group;
        $live->replay_url = json_encode($record_info);
        $this->Lives->save($live);
        $this->loadComponent('TextareaCache');
        $this->loadComponent('ContentFormat');
        $content  = $this->ContentFormat->clean($content)[0];
        $this->TextareaCache->update('lives', $id, $content);
        $this->loadComponent('LiveCache');
        $this->LiveCache->deleteCache($id);
        $this->LiveCache->deleteList();
        $this->G->success("Success");
    }

    /*
     * create by phpstorm
     * author：Ming
     * date：2018.11.26
     * ps： 获取直播录制信息
     * */
    public function record()
    {
        $data = $this->request->getData();
        if(empty($data)){
            $this->G->error('Data_error');
            return null;
        }
        $event_type = $this->request->getData('event_type');
        if($event_type != 100){
            echo 'code:0';
            exit;
        }
        $stream_id = $this->request->getData('stream_id');
        if(empty($stream_id)){
            $this->G->error('Id_error');
            return null;
        }
        $arr = explode('_',$stream_id);
        $stream_id = $arr[1];
        $lives = $this->Lives->findById($stream_id)->select(['id'])->first();
        if(!$lives){
            $this->G->error('Data_not_found');
            return null;
        }
        $live = $this->Lives->newEntity();
        $live->record_info = json_encode($data);
        $live->id = $stream_id;
        $lives_save = $this->Lives->save($live);
        if($lives_save){
            echo 'code:0';
            exit;
        }else{
            $this->G->error('save_error');
            return null;
        }
    }
}
?>